{{ template "layout/header" .}}
<link rel="stylesheet" href="/static/css/ckstyles.css">
<script src="/static/js/ck5b/ckeditor.js"></script>
<main id="body">
    <div class="container">
        <div class="row">
            <div class="col-lg-10 mx-auto">
                <div class="card">
                    <div class="card-header">
                        高级回复
                    </div>
                    <div class="card-body">
                        <form action="/api/v1/thread/{{.thread_id}}/post" method="post" id="advance_reply_form"
                            class="d-block">
                            <input type="hidden" id="quotetid" name="threadid" value="{{.thread_id}}">
                            <input type="hidden" id="docutype" name="docutype" value="0">
                            <div class="message mt-1">
                                <textarea class="form-control" id="editor1" placeholder="内容" name="message"></textarea>
                            </div>
                            <div class="text-muted mt-2 small">
                                <div class="d-flex justify-content-between">
                                    <div class="attachlist_parent">
                                        <a class="small text-left" href="javascript:void(0)">
                                            <label class="addattach" id="addattach">
                                                <i class="icon-folder-open-o"></i>
                                                添加附件
                                                <input type="file" id="add_attach" multiple="multiple"
                                                    class="invisible">
                                            </label>
                                        </a>
                                    </div>
                                    <div>
                                        <button id="postsubmit" type="button" class="btn btn-sm btn-secondary"
                                            id="submit" data-loading-text="正在提交..."> 回帖 </button>
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
            <a role="button" class="btn btn-secondary btn-block xn-back col-lg-6 mx-auto mb-3"
                href="javascript:history.back();">返回</a>
        </div>
    </div>
</main>
<script>
    var myeditor = null;
    ClassicEditor.create(document.querySelector('#editor1'), {

        toolbar: {
            items: [
                'exportPdf',
                'heading',
                '|',
                'bold',
                'italic',
                'underline',
                'fontColor',
                'fontSize',
                'fontFamily',
                'highlight',
                'alignment',
                'link',
                'bulletedList',
                'numberedList',
                '|',
                'indent',
                'outdent',
                '|',
                'imageUpload',
                'blockQuote',
                'insertTable',
                'mediaEmbed',
                'undo',
                'redo',
                '|',
                'codeBlock',
                'code',
                'horizontalLine'
            ]
        },
        language: 'zh-cn',
        image: {
            toolbar: [
                'imageTextAlternative',
                'imageStyle:full',
                'imageStyle:side'
            ]
        },
        table: {
            contentToolbar: [
                'tableColumn',
                'tableRow',
                'mergeTableCells'
            ]
        },
        licenseKey: '',
        ckfinder:{
            'uploadUrl':'/api/v1/image/upload',
        },

    })
        .then(editor => {
            myeditor = editor
        })
        .catch(error => {
            console.error('Oops, something went wrong!');
            console.error(error);
        });

    var qrform = $("#advance_reply_form")
    var jsubmit = $('#postsubmit');
    var attachUploader = $("#add_attach");
    var jattachparent = $('.attachlist_parent');
    var maxSize = 1 * 1024 * 1024

    qrform.on("keydown", function () {
        if (event.keyCode == 13) {
            return false;
        }
    })

    jsubmit.on('click', function () {
        var attachfiles = "";
        if (jattachparent.find('.attachlist').length) {
            console.log($('.attachlist').find("li").length, $('.attachlist').find("li"))
            var attachfiles = ""
            $('.attachlist').find("a[class='attachfile']").each(function () {
                attachfiles += "," + $(this).attr("href") + "|"
                attachfiles += $(this).attr("orgfilename")
            })
            attachfiles = trimChar(attachfiles, ',', 'left');
            console.log(attachfiles);
        }

        // return

        if (myeditor.getData().length == 0) {
            $.alert("亲，写点什么再提交吧 ^_^")
            return;
        }

        qrform.reset();
        jsubmit.button('loading');
        var postdata = qrform.serializeObject();
        postdata.message = myeditor.getData();
        postdata.attachfiles = attachfiles;
        console.log(postdata)

        $.xpost(qrform.attr('action'), postdata, function (code, message) {
            console.log(code, ":", message)
            if (code == 200) {
                $.alert("回复成功")
                setTimeout(function () {
                    // addNewPostElement()
                    history.back()
                }, 2000)
            } else if (code < 0) {
                $.alert(message);
                jsubmit.button('reset');
            } else {
                jform.find('[name="' + code + '"]').alert(message).focus();
                jsubmit.button('reset');
            }
        });

        return false;
    });

    function afterAddNewThread() {
        var jsubmit = $('#postsubmit')
        jsubmit.button('reset');
    }

    function trimChar(str, char, type) {
        if (char) {
            if (type == 'left') {
                return str.replace(new RegExp('^\\' + char + '+', 'g'), '');
            } else if (type == 'right') {
                return str.replace(new RegExp('\\' + char + '+$', 'g'), '');
            }
            return str.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
        }
        return str.replace(/^\s+|\s+$/g, '');
    }

    attachUploader.on('change', function (e) {
        sessionStorage.setItem("test", 1)
        var fd = new FormData()
        attachfile = attachUploader[0].files[0]
        console.log(attachfile)

        var filesSize = attachfile.size
        // 禁止上传大于1m的文件
        console.log(attachfile.size)
        if (filesSize > maxSize) {
            $.alert("文件大于1M，不能上传")
            return
        }

        fd.append("upload", attachfile)
        $.ajax({
            url: "/api/v1/attach/upload",
            data: fd,
            type: "POST",
            contentType: false,
            processData: false,
            success: function (res) {
                //成功
                console.log(res)
                // return
                if (res.code == 200) {
                    // 并发下会 服务端 session 写入会有问题，由客户端控制改为串行
                    if (!jattachparent.find('.attachlist').length) {
                        jattachparent.append('<fieldset class="fieldset"><legend>上传的附件</legend><ul class="attachlist"><ul></fieldset>');
                    }

                    // 添加福建区域
                    message = res.data
                    addAttachLi(message.url, message.filetype, 1, message.orgfilename)

                    $.alert("上传成功")
                    /*setTimeout(function(){
                        location.reload()
                    }, 5000)*/
                } else {
                    $.alert(res.message)
                    return
                }
            }
        })
    });

    function addAttachLi(url, filetype, aid, orgfilename) {
        $('.attachlist').append('<li aid="' + aid + '"><a class="attachfile" orgfilename="' + orgfilename + '"  href="' + message.url + '" target="_blank"><i class="icon filetype ' + filetype + '"></i> ' + orgfilename + '</a> <a href="javascript:void(0);" class="delete ml-2"><i class="icon-remove"></i> 删除</a></li>');
    }

</script>
{{ template "layout/footer" .}}
